package com.ctg.behavior.calc.impala.builder.userpath;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;

import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.ctg.behavior.calc.common.CtPathNode;
import com.ctg.behavior.calc.utils.CtCalcPropertyUtils;
import com.ctg.behavior.common.calc.CtCalcPropertyType;
import com.ctg.behavior.common.consts.CtCalcConsts;
import com.ctg.behavior.common.consts.CtFieldConsts;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class CtUserPathCalcNodeBuilder {

	public List<CtPathNode> doBuilder(Integer columnIndex, String userIdsSQL, final List<LinkedHashMap<String, Object>> queryRows, List<String> byFields) {

		List<CtPathNode> results = new ArrayList<>();
		log.info("Node-queryRows={}", JSON.toJSONString(queryRows));

		Integer seqNo = 1;
		for (LinkedHashMap<String, Object> oneRow : queryRows) {

			// 1. 取出事件标识及对应的计算数值
			Integer total = Integer.valueOf(oneRow.get(CtFieldConsts.FIELD_KEY_TOTAL).toString());
			String eventId = oneRow.get(CtFieldConsts.FIELD_KEY_EVENT).toString();
			// 若本节点的计算结果为0，则该节点不可能有下级节点
//			if (0 == total) {
//				continue;
//			}

			// 2. 填充PathNode基本信息
			CtPathNode pathNode = new CtPathNode();
			pathNode.setEventId(eventId);
			pathNode.setTotal(total);
			pathNode.setSeqNo(seqNo++);
			pathNode.setColumnIndex(columnIndex);
			pathNode.setUserIdsSQL(userIdsSQL);

			// 3. 若该事件指定了分组属性,则取出该属性值
			CtCalcPropertyType pType = CtCalcPropertyUtils.findField(eventId, byFields);
			if (null != pType && !CtCalcConsts.MEASURE_TYPE_TIMES.equals(pType.getProperty())) {
				String byValue = null;
				if (null != oneRow.get(pType.getProperty())) {
					byValue = oneRow.get(pType.getProperty()).toString();
				}
				pathNode.setByProperty(pType.getProperty());
				pathNode.setByValue(String.valueOf(byValue));
			}

			// 加入返回结果数组中
			results.add(pathNode);
		}

		log.info("Node-results={}", JSON.toJSONString(results));

		return results;

	}

}
